package com.song.support.config.security;

import cn.hutool.core.util.ObjectUtil;
import com.song.common.domain.entity.UmsMenu;
import com.song.common.domain.entity.UmsRole;
import com.song.common.domain.entity.UmsSysUser;
import com.song.common.domain.vo.LoginUserVO;
import com.song.common.mapper.UmsMenuMapper;
import com.song.common.mapper.UmsSysUserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserDetailService implements UserDetailsService {

    private final UmsSysUserMapper sysUserMapper;
    private final UmsMenuMapper menuMapper;

    public SysUserDetailService(UmsSysUserMapper sysUserMapper, UmsMenuMapper menuMapper) {
        this.sysUserMapper = sysUserMapper;
        this.menuMapper = menuMapper;
    }

    /**
     * 实现方法，在此方法中根据用户明查询用户
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO: 验证账号类型（用户名、手机号、邮箱）
        int accountType = 0;
        UmsSysUser sysUser = sysUserMapper.selectUserByAccount(username, accountType);
        // 权限查询是根据角色查询的，首先获得所有的角色id
        if (ObjectUtil.isNotNull(sysUser)) {
            List<UmsRole> roleList = sysUser.getRoleList();
            List<Long> roleIds = roleList.stream().map(UmsRole::getRoleId).toList();
            // 根据角色id查询出菜单
            List<UmsMenu> menuList = menuMapper.selectMenuListByRoleIds(roleIds);
            // 获取菜单数组中的权限字段
            List<String> permsList = menuList.stream().map(UmsMenu::getPerms).toList();
            sysUser.setPerms(permsList);
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setUmsSysUser(sysUser);
        return loginUserVO;
    }
}
